#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int min(int x, int y, int z)
    {
        int ret = x < y ? x : y;
        return ret < z ? ret : z;
    }

    int minFallingPathSum(vector<vector<int>>& matrix) {
        int n = matrix.size();
        vector<vector<int>> dp(n + 1, vector<int>(n + 2, 1e9));
        for (int i = 0; i < n + 2; i++)
        {
            dp[0][i] = 0;
        }

        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= n; j++)
            {
                dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i - 1][j + 1]) + matrix[i - 1][j - 1];
            }
        }
        int MIN = dp[n][1];
        for (int i = 2; i <= n; i++)
        {
            if (dp[n][i] < MIN)
            {
                MIN = dp[n][i];
            }
        }
        return MIN;

    }
};